
let sdk = window['sdk'] = window['sdk'] ? window['sdk'] : {}
class WXShare {
    //由于微信无法得到分享结果，所以以时间来判断是否成功。
    time = 0;

    callback;

    data;
    channel;
    constructor(channel, cfg) {
        this.channel = channel;
        this.data = cfg;

        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });

        wx.updateShareMenu({
            withShareTicket: true
        })

        wx.onShareAppMessage(() => {
            // 用户点击了“转发”按钮
            console.log(" this.getData(0) ", this.getData(0))
            return this.getData(0)
        })
        wx.onShow(() => {
            this.backGame()
        })
    }


    showShare(index, func) {
        this.callback = func;
        let data = this.getData(index)
        console.log(' data ', data)
        wx.shareAppMessage(data)
        this.state = sdk.SDKState.open;
        this.time = Date.now();
    }

    shareWithUrl(index, url, func) {
        this.callback = func;
        let data = this.getData(index)
        data[ADName.imageUrl] = url;
        wx.shareAppMessage(data)
        this.state = sdk.SDKState.open;
        this.time = Date.now();
    }

    getData(index) {
        let data = this.data.shares[index]
        return data;
    }



    backGame() {
        if (this.state == sdk.SDKState.open) {
            this.state = sdk.SDKState.close;
            if (this.callback) {
                let disTime = Date.now() - this.time
                if (disTime >= 3000) {
                    this.callback(sdk.ResultState.YES);
                } else {
                    this.callback(sdk.ResultState.NO);
                }
                this.callback = null;
            }
        }
    }


}

class WXSDK {

    constructor() {

    }
    p;
    share;
    init(p, config) {
        this.p = p ? p : window['wx'];
        this.config = config;
        this.vedioAd = {}
        this.customAd = {}
        console.log('this.config  ', this.config)
        console.log('this.rewardedAd  ', this.vedioAd)
        this.share = new WXShare(this, this.config.share);
    }

    getShare() {
        return this.share;
    }
    showToast(message) {
        this.p.showToast({
            title: message,
            icon: 'success',
            duration: 2000
          })
    }
    hideCustomAd(index) {

    }
    showCustomAd(index, param) { }
    // getVisibleSize() {
    //     if (window['cc']) {
    //         return cc.view.getVisibleSize();
    //     } else {
    //         return { width: 0, height: 0 }
    //     }
    // }

    // getCustomAdSize() {
    //     let size = this.getVisibleSize()
    //     // let r = size.height > size.width
    //     var defaultSize = (size.height / size.width) ? { height: 1280, width: 720 } : { width: 1280, height: 720 }
    //     let width = 720 * ((size.height / size.width) > (defaultSize.height / defaultSize.width) ? size.width / defaultSize.width : size.height / defaultSize.height);
    //     return width;
    // }

    // getClientScaleX() {
    //     return 1;
    // }
    // getClientScaleY() {
    //     return 1;
    // }
    // getCustomAdStyle(_dir) {
    //     let r = 720 / 525;
    //     let sys = this.p.getSystemInfoSync()
    //     this.width = this.getCustomAdSize();
    //     this.height = this.width / r;
    //     console.log(' r ', r, ' sys.screenWidth  ', sys.screenWidth, ' width ', this.width, ' height ', this.height, _dir)
    //     let size = this.getVisibleSize()
    //     switch (_dir) {
    //         case sdk.SDKDir.MID:
    //             return {
    //                 left: (size.width - this.width) / 2 * this.getClientScaleX(),
    //                 top: (size.height - this.height) / 2 * this.getClientScaleY()
    //             }
    //         case sdk.SDKDir.BOTTOM_MID:
    //             return {
    //             }
    //         default:
    //             return {
    //             }

    //     }

    // }
    createCustomAd(index, param) {
        if (!this.p.createCustomAd) {
            return;
        }
        let ad = this.getAd(sdk.ADName.CustomAd, index)
        if (!ad) {
            return;
        }
        let customAd = this.p.createCustomAd({
            adUnitId: ad,
            adIntervals: 30,
            style: this.getRealStyle(param),
        });
        customAd.onError((err) => {

        })
        customAd.onLoad(() => {
            customAd.show();
        })
        return customAd;
    }

    hideCustomAd(index) {
        if (this.customAd[index]) {
            this.customAd[index].hide();
        }
    }

    destroyCustomAd(index) {
        if (this.customAd[index]) {
            this.customAd[index].destroy();
            this.customAd[index] = null;
        }
    }

    showGridAd(index, param) {
        this.destroyCustomAd(index);
        this.customAd[index] = this.createCustomAd(index, param)
    }

    showMultipleGridAd(index, param) {
        this.destroyCustomAd(index);
        this.showGridAd(index, param)
    }
    hideMultipleGridAd(index) {
        this.hideCustomAd(index)
    }

    closeMultipleGridAd(index) {
        this.destroyCustomAd(index)
    }
    
    showMatrixAd(index, param) {
        this.destroyCustomAd(index);
        this.showGridAd(index, param)
    }

    closeMatrixAd() {
        this.destroyCustomAd(index)
    }

    createInsertAd(index) {
        if (!this.p.createInterstitialAd) {
            return;
        }

        let ad = this.getAd(sdk.ADName.InsertAd, index)
        if (!ad) {
            return;
        }

        const interstitialAd = this.p.createInterstitialAd({
            adUnitId: ad
        });

        interstitialAd.onError(err => {
            console.log("插屏广告加载失败", err);
        });

        interstitialAd.onClose(() => {
            console.log("interstitialAd onClose");
        });

        interstitialAd.onLoad(() => {
            console.log("interstitialAd onLoad");
            interstitialAd.show()
        });

        return interstitialAd
    }

    showInsertAd(index) {
        this.closeInsertAd();
        this.interstitialAd = this.createInsertAd(index)
    }

    exitApplication() {

        if (this.p.exitMiniProgram) {
            console.log('exitApplication');
            this.p.exitMiniProgram({
                success: () => {

                },
                fail: () => {

                },
                complete: () => {
                }
            })
        }

    }

    closeInsertAd(index) {
        if (this.interstitialAd) {
            this.interstitialAd.destroy();
            this.interstitialAd = null;
        }
    }

    preloadRewaredAd(index) {
        let ad = this.createRewaredAd(index)
        if (ad) {
            this.vedioAd[index] = { ad: ad, callback: null, state: 0, autoPlay: false }
        }
    }
    createRewaredAd(index) {
        if (!this.p.createRewardedVideoAd) {
            return;
        }
        let ad = this.getAd(sdk.ADName.RewaredAd, index)
        if (!ad) {
            return;
        }
        const rewardedAd = this.p.createRewardedVideoAd({
            adUnitId: ad,
        });
        rewardedAd.onError(err => {
            console.log("激励视频广告加载失败", err);
            let obj = this.vedioAd[index]
            if (obj) {
                if (obj.callback) {
                    obj.callback(sdk.ResultState.NO)
                }
            }

        });
        rewardedAd.onLoad((res) => {//微信每次关闭会自动加载。
            console.log('激励视频广告加载完成-onload触发', JSON.stringify(res));
            let obj = this.vedioAd[index]
            if (obj) {
                obj.state = 1;
                if (obj.autoPlay) {
                    obj.autoPlay = false;
                    obj.ad.show().then(() => {
                        console.log('激励视频广告展示完成');
                    }).catch((err) => {
                        console.log('激励视频广告展示失败', JSON.stringify(err));
                    })

                }
            }
        })
        const func = (res) => {
            console.log('视频广告关闭回调')
            let obj = this.vedioAd[index]
            if (obj.callback) {
                if (res && res.isEnded) {
                    console.log("正常播放结束，可以下发游戏奖励");
                    obj.callback(sdk.ResultState.YES)
                } else {
                    obj.callback(sdk.ResultState.NO)
                    console.log("播放中途退出，不下发游戏奖励");
                }
            }

        }
        rewardedAd.onClose(func);
        return rewardedAd;
    }

    loadRewaredAd(index) {
        if (!this.vedioAd[index]) {
            let ad = this.createRewaredAd(index);
            if (ad) {
                this.vedioAd[index] = { ad: ad, callback: null, state: 0, autoPlay: false }
            }
        } else {
            if (this.vedioAd[index]) {
                this.vedioAd[index].ad.load();
            }
        }
    }

    showRewaredAd(index, callback) {
        console.log(' this.rewardedAdd ', this.vedioAd)
        let obj = this.vedioAd[index];
        if (!obj) {
            let ad = this.createRewaredAd(index);
            if (ad) {
                this.vedioAd[index] = { ad: ad, callback: callback, state: 0, autoPlay: true }
            }
        } else {
            obj.callback = callback;
            if (obj.state == 0) {
                obj.autoPlay = true;
                obj.ad.load();
            } else {
                obj.ad.show().then(() => {
                    console.log('激励视频广告展示完成');
                }).catch((err) => {
                    console.log('激励视频广告展示失败', JSON.stringify(err));
                })
            }

        }

    }




    loadBannerAd(index, data) {
        this.bannerAd = this.createBannerAd(index)
    }

    getRealStyle(param) {
        let winSize = this.p.getSystemInfoSync();
        let style = param.style;
        return sdk.getRealStyle(style, winSize)

    }

    createBannerAd(index, param) {
        if (!this.p.createBannerAd) {
            return;
        }
        //style内无需设置任何字段，banner会在屏幕底部居中显示，
        // 没有style字段，banner会在上边显示
        // 1053以及以上版本支持属性设置
        let ad = this.getAd(sdk.ADName.BannerAd, index)
        if (!ad) {
            return;
        }
        var bannerAd = this.p.createBannerAd({
            adUnitId: ad,
            adIntervals: 30,
            style: this.getRealStyle(param)
        });
        bannerAd.onError(err => {
            console.log("banner广告加载失败", err);
        });
        bannerAd.onClose(() => {
            console.log("banner广告onClose");
        })

        bannerAd.onResize((size) => {
            console.log("banner onResize", size);
            let style = bannerAd.style;
            bannerAd.style = sdk.getResizeStyle(style, size);
        })
        return bannerAd;
    }

    showBannerAd(index, param) {
        if (!this.bannerAd) {
            this.bannerAd = this.createBannerAd(index, param)
        }
        if (this.bannerAd) {
            this.bannerAd.show().then(() => {
                console.log('banner广告展示完成');
            }).catch((err) => {
                console.log('banner广告展示失败', JSON.stringify(err));
            })
        }
    }

    hideBannerAd() {
        if (this.bannerAd) {
            this.bannerAd.show().hide(() => {
                console.log('banner广告展示完成');
            }).catch((err) => {
                console.log('banner广告展示失败', JSON.stringify(err));
            })
        }
    }

    closeBannerAd() {
        if (this.bannerAd) {
            this.bannerAd.destroy()
            this.bannerAd = null;
        }
    }

    getAd(name, index) {
        let cfg = this.config.ads[name];
        if (!cfg) {
            return;
        }
        let ids = cfg.ids;
        if (!ids) {
            return;
        }
        let ad = ids[index]
        return ad;
    }

    createBoxBannerAd(index) {
        // if (this.p.createBoxBannerAd) {
        //     let ad = this.getAd(sdk.ADName.BoxBannerAd, index)
        //     if (!ad) {
        //         return;
        //     }
        //     let boxBannerAd = this.p.createBoxBannerAd({
        //         posId: ad
        //     })
        //     boxBannerAd.onError(function (err) { console.log("盒子横幅广告加载失败", err) })
        //     return boxBannerAd;
        // } else {
        //     console.log('暂不支持互推盒子相关 API')
        //     return null;
        // }
    }

    // 结算页、游戏开始页等适合展示的场景调用
    showBoxBannerAd(index) {
        // this.closeBoxBannerAd()
        // if (!this.boxBannerAd) {
        //     this.boxBannerAd = this.createBoxBannerAd(index)
        // }
        // if (this.boxBannerAd) {
        //     // 广告数据加载成功后展示
        //     this.boxBannerAd.show().then(function () {
        //         console.log('show success')
        //     }).catch(function (error) {
        //         console.log('show fail with:' + error.errCode + ',' + error.errMsg)
        //     })
        // }
    }

    hideBoxBannerAd() {
        // if (this.boxBannerAd) {
        //     this.boxBannerAd.hide().then(function () {
        //         console.log('hide success')
        //     }).catch(function (error) {
        //         console.log('hide fail with:' + error.errCode + ',' + error.errMsg)
        //     })
        // }
    }

    // 场景切换等需要关闭时调用
    closeBoxBannerAd() {
        // if (this.boxBannerAd) {
        //     this.boxBannerAd.destroy()
        //     this.boxBannerAd = null;
        // }
    }

    createBoxPortalAd(index, param) {

        // if (this.p.createBoxPortalAd) {
        //     let ad = this.getAd(sdk.ADName.BoxPortalAd, index)
        //     if (!ad) {
        //         return;
        //     }
        //     let marginTop = 200;
        //     let image = ''
        //     if (param) {
        //         if (param.marginTop != undefined) {
        //             marginTop = param.marginTop
        //         }
        //         if (param.image) {
        //             image = param.image
        //         }
        //     }
        //     let boxPortalAd = this.p.createBoxPortalAd({
        //         posId: ad,
        //         image: image,
        //         marginTop: marginTop
        //     })
        //     boxPortalAd.onError(function (err) {
        //         console.log("盒子九宫格广告加载失败", err)
        //     })
        //     boxPortalAd.onClose(function () {
        //         console.log('close')
        //         if (boxPortalAd.isDestroyed) {
        //             return
        //         }
        //         // 当九宫格关闭之后，再次展示Icon
        //         boxPortalAd.show()
        //     })
        //     return boxPortalAd;

        // } else {
        //     console.log('暂不支持互推盒子相关 API')
        //     return null;
        // }
    }

    // 游戏首页等适合展示Icon的场景常驻展示（每次回到此页面均调用一次）
    showBoxPortalAd(index) {
        // this.closeBoxPortalAd();
        // if (!this.boxPortalAd) {
        //     this.boxPortalAd = this.createBoxPortalAd(index)
        // }
        // if (this.boxPortalAd) {
        //     // 广告数据加载成功后展示
        //     this.boxPortalAd.show().then(function () {
        //         console.log('show success')
        //     })
        // }
    }
    // 场景切换等需要关闭时调用
    closeBoxPortalAd() {
        // if (this.boxPortalAd) {
        //     this.boxPortalAd.isDestroyed = true
        //     this.boxPortalAd.destroy()
        //     this.boxPortalAd = null;
        // }
    }
    showDrawerAd(index, param) {

    }
}

window['wx_sdk'] = WXSDK;